<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="100px" @submit.native.prevent>
			<el-form-item :label="$t('attendance_group_name')" prop="attendanceGroupName">
				<el-input v-model="queryParams.attendanceGroupName" :placeholder="$t('please_enter', {
			name: $t('attendance_group_name'),
		})
			" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item :label="$t('attendance_group_code')" prop="attendanceGroupCode">
				<el-input v-model="queryParams.attendanceGroupCode" :placeholder="$t('please_enter', {
			name: $t('attendance_group_code'),
		})
			" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('search')
					}}</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('reset') }}</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['checkWork:checkWorkGroup:add']">{{ $t('add') }}</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange" border :max-height="tableHeight">
			<el-table-column :label="$t('attendance_group_name')" align="center" prop="attendanceGroupName"
				:show-overflow-tooltip="true" />
			<el-table-column :label="$t('attendance_group_code')" align="center" prop="attendanceGroupCode"
				:show-overflow-tooltip="true" />
			<el-table-column :label="$t('remarks')" align="center" prop="remark" :show-overflow-tooltip="true" />
			<el-table-column :label="$t('action')" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
						v-hasPermi="['checkWork:checkWorkGroup:view']">{{ $t('view') }}</el-button>
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
						v-hasPermi="['checkWork:checkWorkGroup:edit']">{{ $t('modify') }}</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						v-hasPermi="['checkWork:checkWorkGroup:delete']">{{ $t('delete') }}</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" :page-sizes="[10, 20, 30, 50, 100, 200]" />

		<!-- 添加或修改考勤组对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="140px" :disabled="lookView"
				@submit.native.prevent>
				<el-card class="box-card" style="margin-bottom: 20px">
					<div slot="header" class="clearfix">
						<span>{{ $t('basic_information') }}</span>
					</div>
					<el-form-item :label="$t('attendance_group_name')" prop="attendanceGroupName">
						<el-input v-model="form.attendanceGroupName" :placeholder="$t('please_enter', {
			name: $t('attendance_group_name'),
		})
			" :show-word-limit="true" />
					</el-form-item>
					<el-form-item :label="$t('attendance_group_code')" prop="attendanceGroupCode">
						<el-input v-model="form.attendanceGroupCode" :placeholder="$t('please_enter', {
			name: $t('attendance_group_code'),
		})
			" :show-word-limit="true" />
					</el-form-item>
					<el-form-item :label="$t('remarks')" prop="remark">
						<el-input v-model="form.remark" :placeholder="$t('please_enter', { name: $t('remarks') })
			" :rows="4" :show-word-limit="true" type="textarea" />
					</el-form-item>
				</el-card>

				<el-card class="box-card" style="margin-bottom: 20px">
					<div slot="header" class="clearfix">
						<span>{{ $t('outside_work_time') }}</span>
					</div>
					<el-form-item :label="$t('attendance_type')" prop="attendanceType">
						<el-select v-model="form.attendanceType" :placeholder="$t('please_select', {
			name: $t('attendance_type'),
		})
			" clearable>
							<el-option v-for="dict in dict.type.check_work_type" :key="dict.value" :label="dict.label"
								:value="dict.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('workday_setting')" v-if="form.attendanceType == 1">
						<el-form-item :label="$t('monday')" style="margin-bottom: 10px" label-width="60px">
							<el-select v-model="form.mon" clearable :placeholder="$t('please_select', { name: '' })">
								<el-option :label="classItem.label" :value="classItem.value" v-for="(
										classItem, classIndex
									) in classesList" :key="classIndex"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item :label="$t('tuesday')" style="margin-bottom: 10px" label-width="60px">
							<el-select v-model="form.tue" clearable :placeholder="$t('please_select', { name: '' })">
								<el-option :label="classItem.label" :value="classItem.value" v-for="(
										classItem, classIndex
									) in classesList" :key="classIndex"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item :label="$t('wednesday')" style="margin-bottom: 10px" label-width="60px">
							<el-select v-model="form.wed" clearable :placeholder="$t('please_select', { name: '' })">
								<el-option :label="classItem.label" :value="classItem.value" v-for="(
										classItem, classIndex
									) in classesList" :key="classIndex"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item :label="$t('thursday')" style="margin-bottom: 10px" label-width="60px">
							<el-select v-model="form.thu" clearable :placeholder="$t('please_select', { name: '' })">
								<el-option :label="classItem.label" :value="classItem.value" v-for="(
										classItem, classIndex
									) in classesList" :key="classIndex"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item :label="$t('friday')" style="margin-bottom: 10px" label-width="60px">
							<el-select v-model="form.fri" clearable :placeholder="$t('please_select', { name: '' })">
								<el-option :label="classItem.label" :value="classItem.value" v-for="(
										classItem, classIndex
									) in classesList" :key="classIndex"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item :label="$t('saturday')" style="margin-bottom: 10px" label-width="60px">
							<el-select v-model="form.sat" clearable :placeholder="$t('please_select', { name: '' })">
								<el-option :label="classItem.label" :value="classItem.value" v-for="(
										classItem, classIndex
									) in classesList" :key="classIndex"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item :label="$t('sunday')" style="margin-bottom: 10px" label-width="60px">
							<el-select v-model="form.sun" clearable :placeholder="$t('please_select', { name: '' })">
								<el-option :label="classItem.label" :value="classItem.value" v-for="(
										classItem, classIndex
									) in classesList" :key="classIndex"></el-option>
							</el-select>
						</el-form-item>
					</el-form-item>
					<template v-if="form.attendanceType == 2">
						<el-form-item prop="onlyLeaderChange">
							<el-checkbox v-model="form.onlyLeaderChange" :true-label="1" :false-label="0">{{
			$t('only_attendance_group_manager')
		}}</el-checkbox>
						</el-form-item>
						<el-form-item prop="canPunch">
							<el-checkbox v-model="form.canPunch" :true-label="1" :false-label="0">{{
			$t('scheduled_shift_employees_can')
		}}</el-checkbox>
						</el-form-item>
						<el-form-item prop="optionalPunch">
							<el-checkbox v-model="form.optionalPunch" :true-label="1" :false-label="0">{{
			$t('employees_can_selected_shifts')
		}}</el-checkbox>
						</el-form-item>
					</template>
					<el-form-item :label="$t('rules_of_statistics')" v-if="form.attendanceType == 3">
						<div class="form-line">
							<span>{{ $t('not_meeting') }}</span>
							<el-input v-model="form.notIncluded" maxlength="3"
								oninput="value=value.replace(/[^\d]/g,'')" style="width: 160px; margin: 0 10px">
								<el-select v-model="form.notIncludedUnit" slot="append" :placeholder="$t('please_select', { name: '' })
			" style="width: 80px">
									<el-option :label="$t('minute')" value="0"></el-option>
									<el-option :label="$t('hour')" value="1"></el-option>
								</el-select>
							</el-input>
							<span>{{ $t('will_counted_working_time') }}</span>
						</div>
						<div class="form-line" style="margin-top: 10px">
							<span>{{ $t('if_equals_exceeds') }}</span>
							<el-input v-model="form.overThan" maxlength="3" oninput="value=value.replace(/[^\d]/g,'')"
								style="width: 160px; margin: 0 10px">
								<el-select v-model="form.overThanUnit" slot="append" :placeholder="$t('please_select', { name: '' })
			" style="width: 80px">
									<el-option :label="$t('minute')" value="0"></el-option>
									<el-option :label="$t('hour')" value="1"></el-option>
								</el-select>
							</el-input>
							<span>{{ $t('it_will_counted') }}</span>
							<el-input v-model="form.defaultDuration" maxlength="3"
								oninput="value=value.replace(/[^\d]/g,'')" style="width: 160px; margin: 0 10px">
								<el-select v-model="form.defaultDurationUnit" slot="append" :placeholder="$t('please_select', { name: '' })
			" style="width: 80px">
									<el-option :label="$t('minute')" value="0"></el-option>
									<el-option :label="$t('hour')" value="1"></el-option>
								</el-select>
							</el-input>
						</div>
					</el-form-item>
				</el-card>

				<el-card class="box-card" style="margin-bottom: 20px">
					<div slot="header" class="clearfix">
						<span>{{ $t('advance_settings') }}</span>
					</div>
					<h3>{{ $t('special_date_setting') }}</h3>

					<el-form-item :label="$t('hide_the_dates_of')" prop="notNeedPunch">
						<el-date-picker type="dates" v-model="form.notNeedPunch" :editable="false"
							value-format="yyyy-MM-dd" :placeholder="$t('please_select', {
			name: $t('hide_the_dates_of'),
		})
			" :append-to-body="false" style="width: 100%"></el-date-picker>
					</el-form-item>
					<el-form-item :label="$t('show_the_dates_of')" prop="needPunch">
						<el-date-picker type="dates" v-model="form.needPunch" :editable="false"
							value-format="yyyy-MM-dd" :placeholder="$t('please_select', {
			name: $t('show_the_dates_of'),
		})
			" :append-to-body="false" style="width: 100%"></el-date-picker>
					</el-form-item>
					<!-- 特殊日期 -->
					<div v-for="(shift, index) in form.attendanceGroupShiftList" :key="index">
						<el-form-item :label="shift.needPunchDay" style="margin-bottom: 10px" label-width="140px">
							<el-select v-model="shift.shiftId" clearable
								:placeholder="$t('please_select', { name: '' })" @change="$forceUpdate()">
								<el-option :label="classItem.label" :value="classItem.value" v-for="(
										classItem, classIndex
									) in classesList" :key="classIndex + index"></el-option>
							</el-select>
						</el-form-item>
					</div>
					<h3>{{ $t('overtime_rules') }}：</h3>
					<el-form-item :label="$t('overtime_rules')" prop="overTimeRule">
						<el-select v-model="form.overTimeRule" clearable :placeholder="$t('please_select', {
			name: $t('overtime_rules'),
		})
			">
							<el-option v-for="dict in dict.type.overtime_rule" :key="dict.value" :label="dict.label"
								:value="dict.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('minimum_unit_of_overtime_hours')" prop="overTimeUnit">
						<el-input v-model="form.overTime" maxlength="4"
							oninput="value=value.replace(form.overTimeUnit==0?/[^\d]/g:/^\d+(\.\d)?$|^\d+(\.\d)?$/.,'')"
							style="width: 160px">
							<el-select v-model="form.overTimeUnit" slot="append"
								:placeholder="$t('please_select', { name: '' })" style="width: 80px">
								<el-option :label="$t('minute')" value="0"></el-option>
								<el-option :label="$t('hour')" value="1"></el-option>
							</el-select>
						</el-input>
					</el-form-item>
					<el-form-item :label="$t('rounding_rules')" prop="carryRule">
						<el-select v-model="form.carryRule" clearable :placeholder="$t('please_select', {
			name: $t('rounding_rules'),
		})
			">
							<el-option v-for="dict in dict.type.carry_rule" :key="dict.value" :label="dict.label"
								:value="dict.value"></el-option>
						</el-select>
					</el-form-item>
					<h3>{{ $t('rules_of_outside_work') }}：</h3>
					<el-form-item prop="fieldClockIn">
						<el-checkbox v-model="form.fieldClockIn" :true-label="1" :false-label="0">{{
			$t('permission_outside_work') }}</el-checkbox>
					</el-form-item>
					<el-form-item prop="fieldClockInRemark">
						<el-checkbox v-model="form.fieldClockInRemark" :true-label="1" :false-label="0">{{
			$t('require_remarks_outside_work')
		}}</el-checkbox>
					</el-form-item>
					<el-form-item prop="fieldClockInNeedPic">
						<el-checkbox v-model="form.fieldClockInNeedPic" :true-label="1" :false-label="0">{{
			$t('need_photo_outside_work') }}</el-checkbox>
					</el-form-item>
					<el-form-item prop="hideDetailedAddress">
						<el-checkbox v-model="form.hideDetailedAddress" :true-label="1" :false-label="0">{{
			$t('allow_hiding_detailed_address')
		}}</el-checkbox>
					</el-form-item>
					<h3>{{ $t('supplementing_attendance_records') }}：</h3>
					<el-form-item prop="submitAmendmentRequest">
						<el-checkbox v-model="form.submitAmendmentRequest" :true-label="1" :false-label="0">{{
			$t('attendance_modification_requests')
		}}</el-checkbox>
					</el-form-item>
					<el-form-item prop="cardReplacement">
						<el-checkbox v-model="form.cardReplacement" :true-label="1" :false-label="0">{{
			$t('allow_supplementing_attendance')
		}}</el-checkbox>
					</el-form-item>
				</el-card>
				<el-card class="box-card" style="margin-bottom: 20px">
					<div slot="header" class="clearfix">
						<span>{{ $t('employer_configuration') }}</span>
					</div>
					<el-form-item :label="$t('select_employing_company')">
						<!-- <el-checkbox-group v-model="form.employerIds">
              <el-checkbox
                v-for="item in employerList"
                :label="item.id"
                :key="item.id"
                >{{ item.employerName }}</el-checkbox
              >
            </el-checkbox-group> -->
						<employerListSelect :employerlist="employerlist" @geteMployerList="geteMployerList">
						</employerListSelect>
					</el-form-item>
				</el-card>
			</el-form>
			<div slot="footer" class="dialog-footer" v-if="!lookView">
				<el-button type="primary" @click="submitForm">{{
			$t('confirm')
		}}</el-button>
				<el-button @click="cancel">{{ $t('cancel') }}</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	listAttendance,
	getAttendance,
	delAttendance,
	addAttendance,
	updateAttendance,
	attendanceGroupShiftList,
} from '@/api/checkWork/checkWorkGroup';
import { listClassesAll } from '@/api/checkWork/classes';
import employerListSelect from '@/views/components/custom/employerListSelect';
export default {
	name: 'Attendance',
	dicts: ['check_work_type', 'overtime_rule', 'carry_rule'],
	components: {
		employerListSelect,
	},
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 考勤组表格数据
			attendanceList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				attendanceGroupName: null,
				attendanceGroupCode: null,
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				attendanceGroupName: [
					{
						required: true,
						message: this.$t('cannot_empty', {
							name: this.$t('attendance_group_name'),
						}),
						trigger: 'blur',
					},
				],
				attendanceGroupCode: [
					{
						required: true,
						message: this.$t('cannot_empty', {
							name: this.$t('attendance_group_code'),
						}),
						trigger: 'blur',
					},
				],
			},
			lookView: false,
			classesList: [],
			employerlist: [],
		};
	},
	created() {
		this.getList();
		this.getData();
	},
	watch: {
		'form.needPunch'(val) {
			console.log('🐛 ~ val:', val);
			if (!this.form.id && val instanceof Array &&val && val.length) {
				console.log(1)
				this.form.attendanceGroupShiftList = val.map((item) => {
					return {
						needPunchDay: item,
						// shiftId: ,
					};
				});
			}

			else if (this.form.id && val instanceof Array && val && val.length) {
				console.log(2)
				let list = this.form.attendanceGroupShiftList.map((item) => {
				  return {
				    id: item.id,
				    shiftId: item.shiftId,
				    needPunchDay: item.needPunchDay,
				  };
				})
				
				console.log("🐛 ~ attendanceGroupShiftList:", list)
				val.forEach(e=>{
					let index = list.findIndex(item => item.needPunchDay === e)
					if(index === -1){
						list.push({
							needPunchDay: e,
							shiftId: null,
						})
					}

				})
				// 如果this.form.attendanceGroupShiftList 中存在 val 没有的日期，则删除
				list = list.filter(item => val.includes(item.needPunchDay))
				this.form.attendanceGroupShiftList = list;

			}
		},
	},

	methods: {

		geteMployerList(list) {
			this.form.employerList = list.map((item) => {
				return {
					...item,
					employerId: item.id,
				};
			});
		},
		/** 查询考勤组列表 */
		getList() {
			this.loading = true;
			listAttendance(this.queryParams).then((response) => {
				this.attendanceList = response.data.records;
				this.total = response.data.total;
				this.loading = false;
			});
		},
		getData() {
			listClassesAll().then((response) => {
				this.classesList = response.data.map((item) => {
					return {
						label: item.shiftName,
						value: item.id,
					};
				});
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				attendanceGroupName: null,
				attendanceGroupCode: null,
				remark: null,
				attendanceType: null,
				onlyLeaderChange: null,
				canPunch: null,
				optionalPunch: null,
				notIncluded: null,
				notIncludedUnit: '1',
				overThan: null,
				overThanUnit: '1',
				defaultDuration: null,
				defaultDurationUnit: '1',

				notNeedPunch: null,
				needPunch: null,
				overTimeRule: null,
				overTimeUnit: null,
				carryRule: null,
				fieldClockIn: null,
				fieldClockInRemark: null,
				fieldClockInNeedPic: null,
				hideDetailedAddress: null,
				submitAmendmentRequest: null,
				cardReplacement: null,
				employerIds: [],
			};
			this.lookView = false;
			this.resetForm('form');
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm('queryForm');
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = this.$t('add');
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const id = row.id || this.ids;
			getAttendance(id).then((response) => {
				this.form = response.data;

				if (this.form.employerList.length > 0) {
					let list = [];
					this.form.employerList.forEach((element) => {
						list.push(element.employer);
					});
					this.employerlist = list;
				}

				if (this.form.notNeedPunch) {
					this.form.notNeedPunch = this.form.notNeedPunch.split(',');
				}
				if (this.form.needPunch) {
					this.form.needPunch = this.form.needPunch.split(',');
				}
				this.open = true;
				this.title = this.$t('modify');
			});
		},
		handleView(row) {
			this.reset();
			const id = row.id || this.ids;
			getAttendance(id).then((response) => {
				this.form = response.data;
				if (this.form.employerList.length > 0) {
					let list = [];
					this.form.employerList.forEach((element) => {
						list.push(element.employer);
					});
					this.employerlist = list;
				}
				this.open = true;
				this.title = this.$t('view');
				this.lookView = true;
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					if (
						this.form.notNeedPunch &&
						this.form.notNeedPunch.length
					) {
						this.form.notNeedPunch =
							this.form.notNeedPunch.join(',');
					}
					if (this.form.needPunch && this.form.needPunch.length) {
						this.form.needPunch = this.form.needPunch.join(',');
					}

					console.log('form', this.form);
	
					if (this.form.id != null) {
						// 编辑attendanceGroupShiftList，有三种情况，新增日期，减少日期，不变日期
						updateAttendance(this.form).then((response) => {
							this.$modal.msgSuccess(
								this.$t('operation_successful')
							);
							this.open = false;
							this.getList();
						});
					} else {

						addAttendance(this.form).then((response) => {
							this.$modal.msgSuccess(
								this.$t('operation_successful')
							);
							this.open = false;
							this.getList();
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids;
			this.$modal
				.confirm(this.$t('delete_data'))
				.then(function () {
					return delAttendance(ids);
				})
				.then(() => {
					this.getList();
					this.$modal.msgSuccess(this.$t('operation_successful'));
				})
				.catch(() => { });
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				'system/attendance/export',
				{
					...this.queryParams,
				},
				`attendance_${new Date().getTime()}.xlsx`
			);
		},
	},
};
</script>
